<script setup>
import { ref, computed } from 'vue'
import { userService } from '../../services/user'
import { Message, Phone, Timer, Calendar, User, Edit } from '@element-plus/icons-vue'
import { useUserStore } from '../../stores/user'
import { showSuccess, showError } from '../../utils/message'

const props = defineProps({
  userId: {
    type: [Number, String],
    default: null
  }
})

const emit = defineEmits(['closed', 'edit'])

// 对话框可见状态
const dialogVisible = ref(false)

// 用户详情数据
const userDetail = ref(null)

// 加载状态
const loading = ref(false)

// 获取userStore
const userStore = useUserStore()

// 角色类型映射
const roleTypeMap = {
  'ROLE_SUPER_ADMIN': 'danger',    // 系统管理员 - 红色
  'ROLE_BUSINESS_STAFF': 'primary', // 业务员 - 蓝色
  'ROLE_OPERATOR': 'warning',      // 操作员 - 黄色
  'ROLE_MANAGER': 'success',       // 负责人 - 绿色
  'ROLE_FINANCE': 'info'           // 财务员 - 灰色
}

// 获取角色标签类型
const getRoleType = (roleCode) => {
  return roleTypeMap[roleCode] || 'info'
}

// 格式化时间
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString()
}

// 状态显示
const statusText = computed(() => {
  if (!userDetail.value) return ''
  return userDetail.value.status === 1 ? '正常' : '禁用'
})

// 状态类型
const statusType = computed(() => {
  if (!userDetail.value) return ''
  return userDetail.value.status === 1 ? 'success' : 'danger'
})

// 获取用户详情
const fetchUserDetail = async (id) => {
  if (!id) return
  
  try {
    loading.value = true
    const data = await userService.getUser(id)
    userDetail.value = data
  } catch (error) {
    console.error('Failed to fetch user detail:', error)
    showError('获取用户详情失败')
  } finally {
    loading.value = false
  }
}

// 打开对话框
const openDialog = async (id) => {
  dialogVisible.value = true
  await fetchUserDetail(id || props.userId)
}

// 处理编辑操作
const handleEdit = () => {
  if (!userDetail.value) return
  
  // 先设置当前用户到store
  userStore.setCurrentUser(userDetail.value)
  
  // 然后发送编辑事件，关闭当前对话框
  // 此时父组件会打开编辑对话框
  setTimeout(() => {
    dialogVisible.value = false
    emit('edit')
  }, 0)
}

// 启用或禁用用户
const toggleUserStatus = async () => {
  if (!userDetail.value) return
  
  try {
    loading.value = true
    const newStatus = userDetail.value.status === 1 ? 0 : 1
    await userService.updateStatus([userDetail.value.id], newStatus)
    
    // 更新本地状态
    userDetail.value.status = newStatus
    showSuccess(newStatus === 1 ? '用户已启用' : '用户已禁用')
  } catch (error) {
    console.error('Failed to update user status:', error)
    showError('更新用户状态失败')
  } finally {
    loading.value = false
  }
}

// 对话框关闭后触发事件
const handleClosed = () => {
  emit('closed')
  userDetail.value = null
}

// 暴露给父组件的方法
defineExpose({
  openDialog
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="用户详情"
    width="550px"
    @closed="handleClosed"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <el-skeleton :loading="loading" animated>
      <template #default>
        <div v-if="userDetail" class="user-detail">
          <div class="user-header">
            <div class="user-avatar">
              <span>{{ userDetail.real_name ? userDetail.real_name.substring(0, 1) : userDetail.username.substring(0, 1) }}</span>
            </div>
            <div class="user-title">
              <h3>{{ userDetail.real_name }}</h3>
              <div class="user-subtitle">
                <el-tag :type="statusType" size="small" effect="light">
                  {{ statusText }}
                </el-tag>
                <span class="username">@{{ userDetail.username }}</span>
              </div>
            </div>
            <div class="user-actions">
              <el-tooltip content="编辑用户" placement="top">
                <el-button
                  type="primary"
                  circle
                  size="small"
                  @click="handleEdit"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip :content="userDetail.status === 1 ? '禁用用户' : '启用用户'" placement="top">
                <el-button
                  :type="userDetail.status === 1 ? 'warning' : 'success'"
                  circle
                  size="small"
                  @click="toggleUserStatus"
                  :loading="loading"
                >
                  <el-icon>
                    <component :is="userDetail.status === 1 ? 'Close' : 'Check'" />
                  </el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </div>
          
          <el-divider />
          
          <div class="info-section">
            <div class="info-item">
              <div class="info-label">
                <el-icon><Message /></el-icon>
                <span>邮箱</span>
              </div>
              <div class="info-value">{{ userDetail.email || '未设置' }}</div>
            </div>
            
            <div class="info-item">
              <div class="info-label">
                <el-icon><Phone /></el-icon>
                <span>手机号</span>
              </div>
              <div class="info-value">{{ userDetail.phone || '未设置' }}</div>
            </div>
            
            <div class="info-item">
              <div class="info-label">
                <el-icon><Timer /></el-icon>
                <span>最后登录时间</span>
              </div>
              <div class="info-value">{{ formatDate(userDetail.last_login_time) }}</div>
            </div>
            
            <div class="info-item">
              <div class="info-label">
                <el-icon><Calendar /></el-icon>
                <span>创建时间</span>
              </div>
              <div class="info-value">{{ formatDate(userDetail.created_at) }}</div>
            </div>
          </div>
          
          <div class="role-section">
            <div class="section-title">
              <el-icon><User /></el-icon>
              <span>角色与权限</span>
            </div>
            <div class="role-list">
              <template v-if="userDetail.roles && userDetail.roles.length > 0">
                <div 
                  v-for="role in userDetail.roles" 
                  :key="role.id"
                  class="role-card"
                  :class="getRoleType(role.code) + '-role'"
                >
                  <div class="role-name">{{ role.name }}</div>
                  <div class="role-code">{{ role.code }}</div>
                  <div class="role-description">{{ role.description }}</div>
                </div>
              </template>
              <el-empty v-else description="暂无角色" :image-size="60" />
            </div>
          </div>
        </div>
      </template>
    </el-skeleton>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleEdit" :disabled="!userDetail">编辑</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.user-detail {
  padding: 0;
}

.user-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  position: relative;
}

.user-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: var(--el-color-primary);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
  margin-right: 16px;
  flex-shrink: 0;
}

.user-title {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
}

.user-title h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
}

.user-subtitle {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-actions {
  display: flex;
  gap: 8px;
  margin-left: auto;
}

.username {
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.info-section {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.info-item {
  padding: 10px;
  border-radius: 6px;
  transition: background-color 0.2s;
}

.info-item:hover {
  background-color: var(--el-fill-color-light);
}

.info-label {
  display: flex;
  align-items: center;
  gap: 6px;
  color: var(--el-text-color-secondary);
  margin-bottom: 4px;
  font-size: 13px;
}

.info-value {
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.role-section {
  margin-top: 16px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: bold;
  margin-bottom: 16px;
  font-size: 15px;
}

.role-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 12px;
}

.role-card {
  border-radius: 6px;
  padding: 12px;
  border-left: 3px solid var(--el-color-info);
  background-color: var(--el-fill-color-light);
  transition: transform 0.2s, box-shadow 0.2s;
}

.role-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.danger-role {
  border-left-color: var(--el-color-danger);
}

.primary-role {
  border-left-color: var(--el-color-primary);
}

.warning-role {
  border-left-color: var(--el-color-warning);
}

.success-role {
  border-left-color: var(--el-color-success);
}

.info-role {
  border-left-color: var(--el-color-info);
}

.role-name {
  font-weight: bold;
  margin-bottom: 4px;
}

.role-code {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-bottom: 8px;
}

.role-description {
  font-size: 13px;
  color: var(--el-text-color-regular);
  line-height: 1.5;
}

.dialog-footer {
  text-align: right;
  width: 100%;
  display: block;
}
</style> 